package ru.usu.gv.gui.actions;

import ru.usu.gv.core.GraphCanvas;
import ru.usu.gv.styles.Style;
import ru.usu.gv.styles.StyleFacade;
import ru.usu.gv.uicomponents.IUIEdgeType;
import ru.usu.gv.uicomponents.IUIVertexType;
import ru.usu.gv.uicomponents.UIEdge;
import ru.usu.gv.uicomponents.UIEdgeTypeRegistry;
import ru.usu.gv.uicomponents.UIGraph;
import ru.usu.gv.uicomponents.UIVertex;
import ru.usu.gv.uicomponents.UIVertexTypeRegistry;

import java.awt.Color;
import java.util.List;

/**
 * @author spupyrev
 * 03.11.2008
 */
public class ApplyStyleAction extends ActionBase
{
	private Style style;

	public ApplyStyleAction(Style style)
	{
		this.style = style;
	}

	@Override
	public void execute()
	{
		UIGraph currentGraph = GraphCanvas.getInstance().getCurrentGraph();

		applyVertexSettings(currentGraph.getVertexes());
		applyEdgeSettings(currentGraph.getEdges());
		applyCommonSettings(currentGraph);

		currentGraph.draw();
	}

	private void applyVertexSettings(List<UIVertex> vertexes)
	{
		double newSize = StyleFacade.getVertexSize(style);
		Color newColor = StyleFacade.getVertexColor(style);
		String vertexTypeId = StyleFacade.getVertexType(style);
		for (UIVertex v : vertexes)
		{
			if (Math.abs(v.getViewItem().getSize() - newSize) > 1e-5)
			{
				v.getViewItem().setSize(newSize);
			}
			if (!newColor.equals(v.getViewItem().getColor()))
			{
				v.getViewItem().setColor(newColor);
			}
			if (!vertexTypeId.equals(v.getVertexType().getId()))
			{
				IUIVertexType vertexType = UIVertexTypeRegistry.findVertexType(vertexTypeId);
				v.changeVertexType(vertexType);
			}
		}
	}

	private void applyEdgeSettings(List<UIEdge> edges)
	{
		Color newColor = StyleFacade.getEdgeColor();
		String edgeTypeId = StyleFacade.getEdgeType();
		for (UIEdge edge : edges)
		{
			if (!newColor.equals(edge.getViewItem().getColor()))
			{
				edge.getViewItem().setColor(newColor);
			}
			if (!edgeTypeId.equals(edge.getEdgeType().getId()))
			{
				IUIEdgeType edgeType = UIEdgeTypeRegistry.findEdgeType(edgeTypeId);
				edge.changeEdgeType(edgeType);
			}
		}
	}

	private void applyCommonSettings(UIGraph currentGraph)
	{
		boolean showVertexLabel = StyleFacade.isShowVertexLabel(style);
		new ShowVertexLabelsAction(showVertexLabel).execute();

		boolean showEdges = StyleFacade.isShowEdges(style);
		new ShowEdgesAction(showEdges).execute();

		boolean isDirected = StyleFacade.isDirectedGraph(style);
		new ChangeGraphDirectionAction(isDirected).execute();
	}

}
